package com.github.postsanf.yinian.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.CardStatusDetailActivity;
import com.github.postsanf.yinian.activity.EveryDayNoticeDialogActivity;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.NewsActivity;
import com.github.postsanf.yinian.activity.TimeGoodsWebActivity;
import com.github.postsanf.yinian.activity.TodayShowActivity;
import com.github.postsanf.yinian.bean.YNNewStaus;
import com.github.postsanf.yinian.bean.YNNewsComment;
import com.github.postsanf.yinian.bean.YNNewsNotice;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNDayNoticeResponse;
import com.github.postsanf.yinian.entity.YNNewsCommentResponse;
import com.github.postsanf.yinian.entity.YNNewsInviteResponse;
import com.github.postsanf.yinian.entity.YNNewsNoticeResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.entity.YNTodayResponse;
import com.github.postsanf.yinian.utils.NotificationUtil;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.LinkedHashMap;


public class DemoIntentService extends GTIntentService {
    private Gson gson = new Gson();
    NotificationUtil notice = null;
    Intent intent;
    int smallIcon = R.drawable.push;
    String ticker = "来了条新的通知";

    public DemoIntentService() {
    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        Log.i("xjs", "onReceiveMessageData -> ");
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        Log.i("xjs", "onReceiveMessageData -> ");
        byte[] payload = msg.getPayload();
        if (payload != null) {
            String data = new String(payload);
            Log.i("xjs", "datadatadata===>" + data.toString());
            int code = -1;
            try {
                JSONTokener jsonParser = new JSONTokener(data);
                JSONObject res = (JSONObject) jsonParser.nextValue();
                code = res.getInt("code");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (notice == null) {
                notice = new NotificationUtil(context, code);
            }
            SharedPreferences sharedPreferences = context
                    .getSharedPreferences(ACTIONs.mymsg, 0);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            switch (code) {
                case 0:
                    // 邀请数据
                    YNNewsInviteResponse resInvite = gson.fromJson(data, YNNewsInviteResponse.class);
                    if (resInvite != null) {
                        editor.putBoolean(ACTIONs.invitebb, true);
                        int invitenum = sharedPreferences.getInt(ACTIONs.invitenum, 0);
                        invitenum++;
                        editor.putInt(ACTIONs.invitenum, invitenum);
                        editor.commit();
                        Intent iIntent = new Intent(ACTIONs.actionDoInvate);
                        iIntent.putExtra(ACTIONs.aInvateDatas, resInvite.getData().get(0));
                        context.sendBroadcast(iIntent);
                        // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddInvate();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                        // 更新通知
                        notice.normal_notification(new Intent(context, NewsActivity.class), smallIcon, ticker, resInvite.getData().get(0).getUnickname(),
                                resInvite.getData().get(0).getIgcontent());
                    }
                    break;
                case 1:
                    // 发表评论
                    YNNewsCommentResponse resComment = gson.fromJson(data, YNNewsCommentResponse.class);
                    if (resComment != null) {
                        editor.putBoolean(ACTIONs.commentbb, true);
                        int commentnum = sharedPreferences.getInt(ACTIONs.commentnum, 0);
                        commentnum++;
                        editor.putInt(ACTIONs.commentnum, commentnum);
                        editor.commit();
                        Intent cIntent = new Intent(ACTIONs.actionDoNews);
                        cIntent.putExtra(ACTIONs.aNewsDatas, resComment.getData().get(0));
                        context.sendBroadcast(cIntent);
                        // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddComment();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                        // 更新通知
                        viewSingleStatus(context, resComment.getData().get(0));
                    }
                    break;
                case 2:
                    // 删除组、成员进组
                    YNNewsNoticeResponse resNotice = gson.fromJson(data, YNNewsNoticeResponse.class);
                    if (resNotice != null) {
                        editor.putBoolean(ACTIONs.notifybb, true);
                        int notifynum = sharedPreferences.getInt(ACTIONs.notifynum, 0);
                        notifynum++;
                        editor.putInt(ACTIONs.notifynum, notifynum);
                        editor.commit();
                        Intent nIntent = new Intent(ACTIONs.actionDoNotice);
                        nIntent.putExtra(ACTIONs.aNoticeDatas, resNotice.getData().get(0));
                        context.sendBroadcast(nIntent);
                        YNNewsNotice ynNewsNotice = resNotice.getData().get(0);
                        if (ynNewsNotice.getNcontent().contains("加入")) {
                            Intent intent1 = new Intent(ACTIONs.AddMember);
                            context.sendBroadcast(intent1);
//                                    sendJoinHuanXinGroup(ynNewsNotice.getGimid(), ynNewsNotice.getUnickname());
                        }
                        if (ynNewsNotice.getNcontent().contains("退出")) {
                            Intent intent1 = new Intent(ACTIONs.deleteMember);
                            context.sendBroadcast(intent1);
                        }
                        // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddNotification();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                        // 更新通知
                        context.sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                        notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, resNotice.getData().get(0).getUnickname(),
                                resNotice.getData().get(0).getNcontent());
                    }
                    break;
                case 3:
                    // 新动态
                    YNNewStaus resStatus = gson.fromJson(data, YNNewStaus.class);
                    if (resStatus != null) {
//                                Intent sIntent = new Intent(ACTIONs.actionDoStatus);
//                                sIntent.putExtra(ACTIONs.aStatusDatas, resStatus.getData()[0].getGroupid());
//                                context.sendBroadcast(sIntent);
                        Intent broadcastIntent = new Intent(context, NoticeBroadcast.class);
                        broadcastIntent.putExtra("groupid", resStatus.getData().get(0).getGroupid());
                        PendingIntent pendingIntent = PendingIntent.
                                getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                        builder.setContentTitle("新动态")
                                .setContentText(resStatus.getData().get(0).getPushContent())
                                .setTicker(ticker)
                                .setContentIntent(pendingIntent)
                                .setSmallIcon(smallIcon)
                                .setAutoCancel(true)
                                .setPriority(NotificationCompat.PRIORITY_MAX)
                                .setDefaults(Notification.DEFAULT_ALL);
                        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                        manager.notify(2, builder.build());
//                                notice.normal_notification(intent1, smallIcon, ticker, "新动态", resStatus.getData().get(0).getPushContent());
                    }
                    break;
                case 4:
                    YNTodayResponse resToday = gson.fromJson(data, YNTodayResponse.class);
                    if (resToday != null) {
                        String text = resToday.getData().get(0).getContent();
                        if (text.contains("#")) {
                            if (text.substring(text.indexOf("#"), text.lastIndexOf("#")).equals("印品商城")) {
                                notice.normal_notification(new Intent(context, TimeGoodsWebActivity.class), smallIcon, ticker, "印品商城",
                                        text);
                            } else if (text.substring(text.indexOf("#"), text.lastIndexOf("#")).equals("今日忆")) {
                                Intent nIntent = new Intent(ACTIONs.actionDoPopToday);
                                context.sendBroadcast(nIntent);
                                notice.normal_notification(new Intent(context, TodayShowActivity.class), smallIcon, ticker, "今日忆",
                                        text);
                            } else {
                                notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, "忆年",
                                        text);
                            }
                        } else {
                            notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, "忆年",
                                    text);
                        }
                    }
                    break;
                case 5:
                    YNDayNoticeResponse resDayNotice = gson.fromJson(data, YNDayNoticeResponse.class);
                    if (resDayNotice != null) {
                        String title = resDayNotice.getData().get(0).getTitle();
                        String content = resDayNotice.getData().get(0).getContent();
                        context.sendBroadcast(new Intent(ACTIONs.actionDoPopEveryDayNotice));
                        Intent[] intents = new Intent[2];
                        intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, MainActivity.class));
                        intents[1] = new Intent(context, EveryDayNoticeDialogActivity.class);
                        notice.normal_notification(intents, smallIcon, ticker, title,
                                content);
//                                notice.normal_notification(new Intent(context, EveryDayNoticeDialogActivity.class), smallIcon, ticker, title,
//                                        content);
                    }
                    break;
            }
        }
        context.sendBroadcast(new Intent(ACTIONs.actionMymessageNums));
        //判断app进程是否存活
        if (!SystemUtils.isAppAlive(context, "com.github.postsanf.yinian")) {
            Log.i("xjs", "launchIntent==>");
            Intent launchIntent = context.getPackageManager().
                    getLaunchIntentForPackage("com.github.postsanf.yinian");
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            context.startActivity(launchIntent);
        }

    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        Log.i("xjs", "onReceiveClientId -> " + "clientid = " + clientid);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.i("xjs", "onReceiveOnlineState -> ");
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        Log.i("xjs", "onReceiveCommandResult -> ");
    }

    public void viewSingleStatus(final Context context, final YNNewsComment ynnewscomment) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(ynnewscomment.getMeid()));
        StringRequest req = new StringRequest(context.getString(R.string.BASE_URL) + context.getString(R.string.ynShowSingleEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resSingleStatus = gson.fromJson(s, YNStatusResponse.class);
//                        Log.i("xjs","viewSingleStatus===ss==>"+s);
                        if (resSingleStatus != null && ReqUtils.isSuccess(resSingleStatus.getCode())) {
                            YNStatus status = resSingleStatus.getData().get(0);
                            if (status == null) {
                                return;
                            }
                            YNSingleton.getInstance().setCurStatus(status);
                            Intent intent = new Intent(context, CardStatusDetailActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            notice.normal_notification(intent, smallIcon, ticker, ynnewscomment.getUnickname(),
                                    ynnewscomment.getMcontent());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }
}
